/**
 * Logger at different levels
 *
 */
class Logger
{
    def int DEBUG = 1
    def int INFO = 2
    def int ERROR = 3

    def currentLevel = INFO
    
    boolean inServletMode = false
    def servletContext = null
    
    def boolean collect = false
    def logLines = []
    
    static Logger logger

    static Logger getLogger()
    {
        if(logger!=null)
        {
            return logger
        }
        else
        {
            logger = new Logger()
        }

        return logger
    }

    static Logger getLogger(servletContext)
    {
        if(logger!=null)
        {
            return logger
        }
        else
        {
            logger = new Logger(servletContext)
        }

        return logger
    }

    private Logger(servletContext)
    {
        this.servletContext = servletContext
        inServletMode = true
    }

    private Logger()
    {
    }

    void initCollection()
    {
        collect = true
        this.logLines = []
    }

    /**
    * returns the collected log lines
    */
    def getCollection()
    {
        return this.logLines 
    }

    void endCollection()
    {
        collect = false
        this.logLines = []
    }

    def debug(msg)
    {
        if(currentLevel == DEBUG)
            logprint msg //"DEBUG - " + new Date() + " - " + msg
    }

    def info(msg)
    {
        if(currentLevel != ERROR)
            logprint msg
    }

    def error(msg)
    {
        logprint msg
    }
    
    def logprint(msg)
    {
        if(collect)
        {
            this.logLines.add(msg)
            //println ("Collected:"+msg)
        }

        // print to servlet log (localhost.-<date>.log)
        if(inServletMode)
        {
            println msg
            // also log to servlet log
            servletContext.log(msg)
        }
        else // print to stdout
        {
            println msg
        }
    }
}
